﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cost.Models;
using NBlock.MVCControl;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Configuration;
using NBlock.Core;

namespace Cost.Controllers
{
    public class DishDeliveryController : Controller
    {
        private readonly ICostRepository<DishDelivery> dishdeliveryRepository;
        private readonly ICostRepository<DishDeliveryItem> dishdeliveryitemRepository;
        private readonly ICostRepository<Storage> storageRepository;
        private readonly ICostRepository<StockRecord> stockrecordRepository;
        private readonly IEnumService enumService;
        private readonly ICostRepository<V_MaterialDeliveryPlan> materialdeliveryplanRepository;

        public DishDeliveryController(ICostRepository<DishDelivery> dishdeliveryRepository,
            ICostRepository<DishDeliveryItem> dishdeliveryitemRepository,
            ICostRepository<Storage> storageRepository,
            ICostRepository<StockRecord> stockrecordRepository,
            IEnumService enumService,
            ICostRepository<V_MaterialDeliveryPlan> materialdeliveryplanRepository)
        {
            this.dishdeliveryRepository = dishdeliveryRepository;
            this.dishdeliveryitemRepository = dishdeliveryitemRepository;
            this.storageRepository = storageRepository;
            this.stockrecordRepository = stockrecordRepository;
            this.enumService = enumService;
            this.materialdeliveryplanRepository = materialdeliveryplanRepository;
        }

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult List(nbPageInfo pager, nbSearchCondition where)
        {
            var pageData = dishdeliveryRepository.GetPageable(pager, m => m.State == "Draft", where);
            var data = pager.ToGridData(pageData);
            return Json(data);
        }

        public ActionResult Edit(string Id, string siteId, string date)
        {
            var data = dishdeliveryRepository.Find(Id) ?? new DishDelivery();
            if (string.IsNullOrEmpty(data.CreateUserId))
            {
                data.State = "Draft";
                if (!string.IsNullOrEmpty(siteId))
                {
                    data.SiteID = ViewBag.SiteID = siteId;
                    ViewBag.Date = date;
                    data.Date = DateTime.Parse(date);
                }
                else
                {
                    data.Date = DateTime.Now;
                }
            }
            return View(data);
        }

        [HttpPost]
        public JsonResult Save(string Id, IList<DishDeliveryItem> detail)
        {
            var data = dishdeliveryRepository.Find(Id) ?? new DishDelivery();
            TryUpdateModel(data);
            data.SiteName = enumService.GetEnumText("ProjectSite", data.SiteID);
            dishdeliveryRepository.Save(data);
            // 先删除所有子表，再保持所有子表数据
            dishdeliveryitemRepository.DeleteAll(m => m.OrderId == Id);
            if (detail != null)
            {
                foreach (var m in detail)
                {
                    m.OrderId = Id;
                    m.MaterialId = m.Id;
                    m.Id = Guid.NewGuid().ToString();
                    m.State = "Draft";
                    dishdeliveryitemRepository.Insert(m);

                    //保存库存记录
                    StockRecord StockRecorddate = new StockRecord()
                    {
                        Id = Guid.NewGuid().ToString(),
                        MaterialId = m.MaterialId,
                        Type = "物流送货",
                        Count = m.DeliveryCount,
                    };
                    stockrecordRepository.Insert(StockRecorddate);
                }
            }
            return Json(AjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult Delete(string id)
        {
            dishdeliveryRepository.Delete(id);
            dishdeliveryitemRepository.DeleteAll(m => m.OrderId == id);
            return Json(AjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult MaterialList(nbPageInfo pager, nbSearchCondition where)
        {
            var pageData = dishdeliveryRepository.GetPageable(pager, where);
            var data = pager.ToGridData(pageData);
            return Json(data);
        }

        [HttpPost]
        public JsonResult EditList(string parentId, string siteId, DateTime? date, nbPageInfo pager, nbSearchCondition where)
        {
            // 从发货计划中产生明细
            if (!string.IsNullOrEmpty(siteId))
            {
                string sql = @"SELECT dbo.Material.Id, '' as OrderId, dbo.Material.Id as MaterialId,
                                dbo.Material.Code, dbo.Material.Name, 0.0 as Price, dbo.Material.Category, SUM(dbo.DishMaterial.Weight * dbo.DishOrderItem.Count) AS OrderCount,
                                SUM(dbo.DishMaterial.Weight * dbo.DishOrderItem.Count) as DeliveryCount,0.0 as SignCount, 'Draft' as State, dbo.DishOrderItem.Name AS DishName
                                , dbo.DishOrderItem.Code AS DishCode, dbo.DishOrderItem.Category AS DishCategory
	                                FROM  dbo.Material 
	                                INNER JOIN dbo.DishMaterial ON dbo.Material.Id = dbo.DishMaterial.MaterialId 
	                                INNER JOIN dbo.DishOrderItem ON dbo.DishMaterial.DishId = dbo.DishOrderItem.DishId
                                Where dbo.DishOrderItem.Date = @Date AND dbo.DishOrderItem.SiteId = @SiteId
                                GROUP BY dbo.DishOrderItem.Date, dbo.DishOrderItem.SiteId,dbo.Material.Id, dbo.Material.Category, dbo.Material.Code, dbo.Material.Name
                                , dbo.DishOrderItem.Name, dbo.DishOrderItem.Code, dbo.DishOrderItem.Category";

                List<SqlParameter> plist = new List<SqlParameter>();
                plist.Add(new SqlParameter("@Date", date.Value));
                plist.Add(new SqlParameter("@SiteId", siteId));
                var context = new DbContext(ConfigurationManager.ConnectionStrings["Cost"].ConnectionString);
                var list = context.Database.SqlQuery<DishDeliveryItem>(sql, plist.ToArray()).ToList();
                foreach (var item in list)
                {
                    item.OrderCount = item.OrderCount / 500;
                    item.DeliveryCount = item.DeliveryCount / 500;
                    if (item.DeliveryCount % 1 > 0)
                    {
                        item.DeliveryCount = Convert.ToInt32(item.DeliveryCount) + 1;
                    }
                    else
                    {
                        item.DeliveryCount = Convert.ToInt32(item.DeliveryCount);
                    }
                    item.SignCount = item.SignCount / 500;
                }
                var fdata = pager.ToGridData(list, list.Count);
                return Json(fdata);
            }
            else
            {
                var list = dishdeliveryitemRepository.GetPageable(pager, m => m.OrderId == parentId, where);
                var fdata = pager.ToGridData(list);
                return Json(fdata);
            }

        }

        public JsonResult MaterialDelivery(string Id)
        {
            var data = dishdeliveryRepository.Find(Id);
            data.State = "Delivery";
            dishdeliveryRepository.Save(data);

            var itemList = dishdeliveryitemRepository.FindAll(m => m.OrderId == Id).ToList();
            foreach (var childitem in itemList)
            {
                var childdata = dishdeliveryitemRepository.Find(childitem.Id);
                childdata.State = "Delivery";
                dishdeliveryitemRepository.Save(childdata);

                var SorageData = storageRepository.Find(s => s.Code == childitem.Code);
                if (SorageData != null)
                {
                    SorageData.ActualStorage -= childitem.DeliveryCount;
                    storageRepository.Save(SorageData);
                }
            }

            return Json(AjaxMessage.Successful);
        }

        #region LookUp
        public ActionResult LookUp()
        {
            return View();
        }

        [HttpPost]
        public JsonResult LookUp(nbPageInfo pager, nbSearchCondition where)
        {
            var list = materialdeliveryplanRepository.GetPageable(pager, where);
            var fdata = pager.ToGridData(list);
            return Json(fdata);
        }
        #endregion
    }
}
